﻿var bg = chrome.extension.getBackgroundPage();
G = bg.SINA;
$(function () {
	if (G.sinaAdpt.getAccessToken()) {
		$('#user_img').attr('src', G.get('imageurl'))
		$('#add_username').text(G.get('screenname')).attr('href', 'http://weibo.com/' + G.get('uid'));
		
		$("#status").keypress(function (e) {
			var status = this.value;
			if (e.ctrlKey && e.which == 13 || e.which == 10) {
				send_status(status);
			} else if (e.shiftKey && e.which == 13 || e.which == 10) {
				send_status(status);
			} else if (e.shiftKey && e.which == 64) {
				atWrap();
				doane(e);
			}
		}).val(G.get('auto_sae_status'));
		
		checkText("status", 140);
		
		document.body.onpaste = paste;
		
		$("#input_at").keyup(function (e) {
			var keyCode = e.keyCode;
			if ((keyCode >= 65 && keyCode <= 90) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode == 46 || keyCode == 8 || keyCode == 32) {
				var wordText = $(this).val();
				if (wordText) {
					$("#autoCm select.all").hide();
					$("#autoCm select.auto").show();
					var lis = [];
					$.each(friends, function (i, v) {
						if (v.name.indexOf(wordText) != -1 || v.py.indexOf(wordText.toLocaleLowerCase()) != -1 || v.pysx.indexOf(wordText.toLocaleLowerCase()) != -1) {
							var li = "<option value=\"@" + v.name + "\">" + v.name + "</option>";
							lis.push(li);
						}
					});
					$("#autoCm select.auto").html(lis.join(""));
				} else {
					$("#autoCm select.auto").hide();
					$("#autoCm select.all").show();
				}
			} else if (keyCode == 38 || keyCode == 40) {
				$("#autoCm select:visible").focus();
			}
		});
		
		$("#autoCm select").keyup(function (e) {
			if (e.keyCode == 13) {
				var v = $(this).val();
				if (v) {
					$("#atWrap").hide();
					$("#input_at").val("");
					$(this).val("");
					insertFace("status", " " + v.join(" "));
				}
			}
		}).mouseup(function (e) {
			if (e.which == 3) {
				var v = $(this).val();
				if (v) {
					$("#atWrap").hide();
					$("#input_at").val("");
					$(this).val("");
					insertFace("status", " " + v.join(" "));
				}
			}
		}).dblclick(function () {
			var v = $(this).val();
			if (v) {
				$("#atWrap").hide();
				$("#input_at").val("");
				$(this).val("");
				insertFace("status", " " + v.join(" "));
			}
		});
	} else {
		$('#login_box').show();	
		$("#login_btn").click(function () {
			G.authorize();
		});
	}
});

function good() {
	$('#status').focus().val("#GodSon分享# 我正在使用Chrome插件--新浪微博助手。https://chrome.google.com/webstore/detail/bebkcfflfplfpjoebbabeejckmjagafh");
	checkText("status", 140);
	send_status();
}

function showtip(tipc) {
	var tip = $("#tipWrap .tip");
	if (!tipc)
		return;
	if (!tip.length) {
		tip = $('<div class="tip">' + tipc + '</div>').appendTo('#tipWrap');
	} else {
		tip.text(tipc);
	}
	tip.fadeIn().delay(2000).fadeOut();
}

function short_url(url, callBack) {
	showtip("短网址生成ing");
	G.post("https://api.weibo.com/2/short_url/shorten.json", {
		url_long : encodeURI(url)
	}, function (resp) {
		callBack.call(this, resp.urls[0].url_short);
	});
}

function createShortUrl() {
	var url = $("#input_url").val();
	if (url && checkUrl(url)) {
		short_url(url, function (surl) {
			var cvalue = $("#status").val();
			$("#status").val(cvalue +" "+ surl);
			checkText("status", 140);
			$("#input_url").val("");
			closewrap("#divWrap");
		});
	}else{
		showtip("地址不正确！必须是http|s开头！");
	}
}

/////////////////////////////
//上传图片
var FILECHECK = {
	"maxFileSize" : 5120000,
	"fileTypes" : "__image/gif__image/jpeg__image/jpg__image/png__"
};
function checkFile(file) {
	var check = true;
	if (file) {
		if (file.size > FILECHECK.maxFileSize) {
			showtip('文件太大，请选择小于5M的文件。');
			check = false;
		}
		if (FILECHECK.fileTypes.indexOf('__' + file.type || file.fileType + '__') < 0) {
			showtip('文件类型不正确，仅支持JPEG,GIF,PNG图片。');
			check = false;
		}
	} else {
		showtip('请选择要上传的图片。');
		check = false;
	}
	return check;
}
function selectFile(fileEle) {
	if (typeof FileReader === 'undefined') {
		showtip('当前浏览器版本不支持上传图片，请升级。');
		G.file = "";
		return;
	}
	unSelectFile("_list");
	var file = fileEle.files[0];
	$("#img_pop").html("");
	
	if (file) {
		showFile(file);
	} else {
		G.file = "";
	}
}

function selectListFile(fileEle) {
	if (typeof FileReader === 'undefined') {
		showtip('当前浏览器版本不支持上传图片，请升级。');
		G.file = "";
		return;
	}
	unSelectFile();
	var files = fileEle.files;
	$("#img_list_pop").html("");
	$("#img_pop").html("");
	
	if (files.length > 0) {
		MakeImageData(files);
	} else {
		G.file = "";
	}
}

function MakeImageData(files){
	var imgas = new Array();
	var settings = JSON.parse(G.get('longSetting'));
	var syimg = new Image();
	if(settings.sy){
		syimg.src = settings.sy;
	}
	for(var i=0;i<files.length;i++){
		var file = files[i];
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.fileName = file.name;
		reader.onload = function (e) {
			var img = new Image();
			img.src = e.target.result;
			img.name = this.fileName.substring(0,this.fileName.lastIndexOf('.'));
			imgas.push(img);
		};
	}
	
	var listents = setInterval(function(){
		if(imgas.length == files.length){
			clearInterval(listents);
			var data = merger(imgas);
			G.file = _dataUrlToBlob(data);
			G.fileData = data;
			showListFile(G.file);
		}
	},500);
	
	function merger(imgs){
		
		if(!imgs && imgs.length == 0) 
			return null;
			
		imgs = imgs.sort(function(a,b){
			return a.name > b.name || a.width > b.width;
		});
		var larger = false;
		var maxWidth = settings.maxWidth;
		for (var i = 0; i < imgs.length; i++) {
			var img = imgs[i];
			if(img.width > settings.maxWidth){
				larger = true;
			}
			if(i == (imgs.length-1) && !larger){
				maxWidth = img.width;
			}
		}
		
		var height = 0;
		for (var i = 0; i < imgs.length; i++) {
			var img = imgs[i];
			if(img.width != maxWidth){
				var pif = maxWidth/img.width;
				img.width = maxWidth;
				img.height = img.height*pif;
			}
			height += img.height;
			imgs[i] = img;
		}
		
		var canvas = document.createElement("canvas");
		var fontHeight = height+2+imgs.length*2;
		var fontWidth = imgs[imgs.length-1].width+4;
		if(syimg.height != 0){
			var w = syimg.width,h = syimg.height;
			if(fontWidth < syimg.width){
				var bl = fontWidth/syimg.width;
				syimg.width = fontWidth;
				syimg.height = h*bl;
			}
		}	
		canvas.width = fontWidth;
		canvas.height = fontHeight + syimg.height;
		
		var ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		ctx.fillStyle = "#fff";
		ctx.fillRect(0, 0, canvas.width, canvas.height);
	
		var dheight = 2;
		for (var i = 0; i < imgs.length; i++) {
			var img = imgs[i];
			var cheight = img.height;
			var cwidth = img.width;
	
			ctx.drawImage(img, 2, dheight, cwidth, cheight);
			dheight += cheight+2;
		}
		
		if(syimg.height != 0){
			var x = 0;
			if(fontWidth - syimg.width > 0){
				x = (fontWidth - syimg.width)/2;
			}
			ctx.drawImage(syimg, x, dheight , syimg.width, syimg.height);
		}
		
		var dataurl = canvas.toDataURL('image/jpeg',parseFloat(settings.imgQuality||1));
		return dataurl;
	}
	
	/**
	 * 将dataUrl转化成Blob对象
	 * 
	 * @param {String} dataurl
	 * @return {Blob} 
	 * @api public
	 */
	function _dataUrlToBlob(dataurl) {
		return dataURLtoBlob(dataurl);
	};
}

function size(bytes) {
	var i = 0;
	while (1023 < bytes) {
		bytes /= 1024;
		++i;
	};
	return i ? bytes.toFixed(2) + ["", " Kb", " Mb", " Gb", " Tb"][i] : bytes + " bytes";
}

function showFile(file, target) {
	var check = checkFile(file);
	if (check) {
		G.file = file;
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function (e) {
			var v = $.trim($('#status').val());
			if (v == "") {
				$("#status").val('分享图片');
				checkText("status", 140);
			}
			$("#img_upload").hide();
			$("#img_select").html(size(file.size));
			$("#img_select").attr("title", "图片");
			$("#img_name").show();
			$("#img_pop").html('<img src="' + e.target.result + '" />');
		};
	} else {
		$("#img_upload").show();
	}
}

function showListFile(file, target) {
	var check = checkFile(file);
	if (check) {
		G.file = file;
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function (e) {
			var v = $.trim($('#status').val());
			if (v == "") {
				$("#status").val('分享图片');
				checkText("status", 140);
			}
			$("#img_list_upload").hide();
			$("#img_list_select").html(size(file.size));
			$("#img_list_select").attr("title", "图片");
			$("#img_list_name").show();
			var r = e.target.result.split(":");
			var src = r[0] + ":image/png;" + r[1];
			$("#img_list_pop").html('<img src="' + src + '" />');
		};
	} else {
		$("#img_list_upload").show();
	}
}

function unSelectFile(target) {
	target = target || "";
	$("#ajax" + target + "img").val("");
	$("#img" + target + "_upload").show();
	$("#img" + target + "_select").html("");
	$("#img" + target + "_select").attr("title", "");
	$("#img" + target + "_name").hide();
	$("#img" + target + "_pop").html('');
	G.file = "";
	var v = $.trim($('#status').val());
	if (v == "分享图片")
		$("#status").val('');
	
	checkText("status", 140);
}

function paste() {
	var items = event.clipboardData.items;
	for (var i = 0; i < items.length; ++i) {
		if (items[i].kind == 'file' && items[i].type == 'image/png') {
			var blob = items[i].getAsFile();
			showFile(blob, true);
		}
	}
	checkText('status', 140);
}

var FACE_HTML = (function(){
	var emotions = JSON.parse(G.get("emotions_tpl"));
	var emotionsStr = [];
	$.each(emotions,function(k,v){
		emotionsStr.push('<lable style="cursor: pointer;padding: 3px;" title="'+k+'">'+v+'</lable>');
	});
	emotionsStr = emotionsStr.join("");
	
	setTimeout(function(){
		$("#faceWrap").html(emotionsStr);
	},2000);
	
	return emotionsStr;
})();

function showFace(showid, xy, type) {
	$("#atWrap").hide();
	$("#divWrap").hide();
	if ($("#faceWrap").html() == "")
		$("#faceWrap").html(FACE_HTML);
	
	$("#faceWrap").toggle(); //slideToggle
	
	var offset = $("#" + xy).offset();
	$("#faceWrap").css("left", 32).css("bottom", 65);
	
	$("#faceWrap lable").unbind('click').click(function () {
		insertFace(showid, $(this).attr("title"));
	});
	
	doane();
	
	$(document.body).click(function (e) {
		$("#faceWrap").hide();
	});
	$(document.body).scroll(function (e) {
		$("#faceWrap").hide();
	});
	
}

function checkFocus(target) {
	var obj = document.getElementById(target);
	if (obj !=null && !obj.hasfocus) {
		obj.focus();
	}
}
function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}
function insertFace(showid, text) {
	var obj = document.getElementById(showid);
	selection = document.selection;
	checkFocus(showid);
	if (!isUndefined(obj.selectionStart)) {
		var opn = obj.selectionStart + 0;
		obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
	} else if (selection && selection.createRange) {
		var sel = selection.createRange();
		sel.text = text;
		try {
			sel.moveStart('character', -strlen(text));
		} catch (e) {}
	} else {
		obj.value += text;
	}
	
	checkText(showid, 140);
}

function doane(event) {
	e = event ? event : window.event;
	if (!e)
		e = getEvent();
	if (e && $.browser.msie) {
		e.returnValue = false;
		e.cancelBubble = true;
	} else if (e) {
		e.stopPropagation();
		e.preventDefault();
	}
}

function insertTopic(topic) {
	if (!topic)
		topic = "请在这里输入自定义话题";

	var inputor = document.getElementById('status');
	var hasCustomTopic = new RegExp('#请在这里输入自定义话题#').test(inputor.value);
	var text = topic,
	start = 0,
	end = 0;
	
	inputor.focus();
	
	if (document.selection) {
		var cr = document.selection.createRange();
		//获取选中的文本
		text = cr.text || topic;
		
		//内容有默认主题，且没选中文本
		if (text == topic && hasCustomTopic) {
			start = RegExp.leftContext.length + 1;
			end = topic.length;
		}
		//内容没有默认主题，且没选中文本
		else if (text == topic) {
			cr.text = '#' + topic + '#';
			start = inputor.value.indexOf('#' + topic + '#') + 1;
			end = topic.length;
		}
		//有选中文本
		else {
			cr.text = '#' + text + '#';
		}
		
		if (text == topic) {
			cr = inputor.createTextRange();
			cr.collapse();
			cr.moveStart('character', start);
			cr.moveEnd('character', end);
		}
		
		cr.select();
	} else if (inputor.selectionStart || inputor.selectionStart == '0') {
		start = inputor.selectionStart;
		end = inputor.selectionEnd;
		
		//获取选中的文本
		if (start != end) {
			text = inputor.value.substring(start, end);
		}
		
		//内容有默认主题，且没选中文本
		if (hasCustomTopic && text == topic) {
			start = RegExp.leftContext.length + 1;
			end = start + text.length;
		}
		//内容没有默认主题，且没选中文本
		else if (text == topic) {
			inputor.value = inputor.value.substring(0, start) + '#' + text + '#' + inputor.value.substring(end, inputor.value.length);
			start++;
			end = start + text.length;
		}
		//有选中文本
		else {
			inputor.value = inputor.value.substring(0, start) + '#' + text + '#' + inputor.value.substring(end, inputor.value.length);
			end = start = start + text.length + 2;
		}
		
		//设置选中范
		inputor.selectionStart = start;
		inputor.selectionEnd = end;
	} else {
		inputor.value += '#' + text + '#';
	}
	
	checkText("status", 140);
}

function shortWrap() {
	$("#atWrap").hide();
	$("#faceWrap").hide();
	var inputor = document.getElementById('status');
	var text = "";
	inputor.focus();
	if (inputor.selectionStart || inputor.selectionStart == '0') {
		var start = inputor.selectionStart;
		var end = inputor.selectionEnd;
		//获取选中的文本
		if (start != end) {
			text = inputor.value.substring(start, end);
		}
		if (text) {
			if (checkUrl(text)) {
				short_url(text, function (shorturl) {
					inputor.value = inputor.value.substring(0, start) + shorturl + inputor.value.substring(end, inputor.value.length);
					checkText("status", 140);
				});
				return;
			}
		}
	}
	$("#divWrap").show();
}

function closewrap(id) {
	$(id).hide();
}
SHOWTIP= false;
function checkText(id, count) {
	var v = $.trim($('#' + id).val());
	var left = calWbText(v, count);
	if (left >= 0) {
		$('#' + id + "_warn").html('还能输入<em>' + left + '</em>字');
		G.tolong = false;
		SHOWTIP = true;
	} else {
		$('#' + id + "_warn").html('已超出<em style="color:red;">' + Math.abs(left) + '</em>字');
		G.tolong = true;
		if (SHOWTIP) {
			showtip("本条微博将以图片形式发送！");
			SHOWTIP = false;
		}
	}
	$('#' + id).height(120);
	var scrollHeight = $('#' + id)[0].scrollHeight;
	if(scrollHeight > 130 && scrollHeight < 300){
		$('#' + id).height(scrollHeight);
	}else if(scrollHeight > 300){
		$('#' + id).height(300);
	}
	G.set('auto_sae_status', v);
	return left >= 0 && v;
}

function calWbText(text, count) {
	var cLen = 0;
	var matcher = text.match(/[^\x00-\xff]/g),
	wlen = (matcher && matcher.length) || 0;
	return Math.floor((count * 2 - text.length - wlen) / 2);
}

function checkUrl(url) {
	return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url);
}

function send_status() {
	if (G.send)
		return;

	var weibo = $.trim($('#status').val());
	if (!weibo)
		return;
	
	$("#send_s").removeClass("send_s").addClass("send_s2");
	$('#status').attr('disabled', true);
	$("#send_loading").show();
	
	function reset() {
		$('#status').attr('disabled', false);
		$('#status').val('');
		$('#status_warn').html('还能输入<em>140</em>字');
		$("#send_s").removeClass("send_s2").addClass("send_s");
		$("#send_loading").hide();
		unSelectFile();
		unSelectFile("_list");
		G.send = false;
		G.img = null;
		G.file = null;
	}
	function ErrorReset() {
		$('#status').attr('disabled', false);
		$("#send_s").removeClass("send_s2").addClass("send_s");
		$("#send_loading").hide();
		G.send = false;
	}
	if($("#img_pop img").length){
		G.img = $("#img_pop img").attr("src");
	}
	G.send_status(weibo,reset,ErrorReset);
}

function atWrap() {
	$("#faceWrap").hide();
	$("#divWrap").hide();
	$("#atWrap").show();
	$("#input_at").focus();
	
	friends = JSON.parse(G.get('friends'));
	
	if (!friends) {
		$("#autoCm select.all").html("<option>好友加载失败！</option>");
	}
	
	if ($("#autoCm select.all").children()[0].text == "好友加载失败！") {
		var lis = [];
		$.each(friends, function (i, v) {
			var li = "<option value=\"@" + v.name + "\">" + v.name + "</option>";
			lis.push(li);
		});
		$("#autoCm select.all").html(lis.join(""));
	}
}
